#include "main/utils.h"
#include "lib/list.h"
using namespace std;

void insertNode(ListNode* head, int value) {
  ListNode* new_node = new ListNode();
  new_node->value = value;
  if (head == nullptr) {
    head = new_node;
    new_node->next = new_node;
    return;
  }
  if (head->next == head) {
    head->next = new_node;
    new_node->next = head;
    return;
  }
  ListNode* max_node = head;
  ListNode* cur_node = head->next;
  while (cur_node != head) {
    if (cur_node->value <= value && cur_node->next->value >= value) {
      new_node->next = cur_node->next;
      cur_node->next = new_node;
      return;
    }
    if (cur_node->value >= max_node->value) {
      max_node = cur_node;
    }
    cur_node = cur_node->next;
  }
  new_node->next = max_node->next;
  max_node->next = new_node;
}

void PrintListLoop(ListNode* root) {
  if (root == nullptr)
    return;
  if (root->next == root) {
    cout << root->value << endl;
    return;
  }
  cout << root->value << " ";
  auto node = root->next;
  while (node != root) {
    std::cout << node->value << " ";
    node = node->next;
  }
  std::cout << std::endl;
}

int main() {
  vector<int> vec = {1, 2, 3, 5, 6, 7};
  int value = 0;
  ListNode* head = CreateList(vec);
  auto node = head;
  while (node->next) {
    node = node->next;
  }
  node->next = head;
  insertNode(head, value);
  PrintListLoop(head);

  return 0;
}
